
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

import AccountLogin from '@/components/AccountLogin.vue'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置NProgress
NProgress.configure({ 
  easing: 'ease',
  speed: 500,
  showSpinner: false,
  trickleSpeed: 200,
  minimum: 0.1
})

// 懒加载包装：失败时重试，仍失败则刷新页面以解决ChunkLoadError
const withChunkRetry = (importer, retries = 2, retryDelayMs = 300) => () =>
  importer().catch(async (error) => {
    const isChunkError = String(error && (error.message || error)).includes('ChunkLoadError')
    if (!isChunkError || retries <= 0) {
      if (isChunkError) {
        // 最后一次仍失败，强制刷新页面
        window.location.reload()
        // 返回一个永不resolve的Promise以阻止后续报错
        return new Promise(() => {})
      }
      throw error
    }
    // 简单重试
    await new Promise((r) => setTimeout(r, retryDelayMs))
    return withChunkRetry(importer, retries - 1, retryDelayMs)()
  })

const routes = [
  { path: '/', component: AccountLogin, name: 'AccountLogin' },
  { path: '/register', component: withChunkRetry(() => import('@/components/AccountRegister.vue')), name: 'AccountRegister' },
  { path: '/newUser', component: withChunkRetry(() => import('@/components/newUser/newUser.vue')), name: 'newUser' },
  { path: '/userHome', redirect: "/userHome/user_repairCenter", name: 'user' },
  {
    path: '/userHome', component: withChunkRetry(() => import('@/components/userHome/userHome.vue')), meta: { auth: true, type: 'user' }, children: [
      { path: 'user_repairCenter', component: withChunkRetry(() => import('@/components/userHome/RepairCenter/repairCenter.vue')), name: 'user_repairCenter', meta: { auth: true, type: 'user' } },
      { path: 'user_repairRecord', component: withChunkRetry(() => import('@/components/userHome/repairRecord/repairRecord.vue')), name: 'repairRecord', meta: { auth: true, type: 'user' } },
      { path: 'charge_on', component: withChunkRetry(() => import('@/components/userHome/repairRecord/chargeOn/chargeOn.vue')), name: 'charge_on', meta: { auth: true, type: 'user' } },
    ]
  },
  { path: '/workerHome', redirect: "/workerHome/worker_repairCenter", name: 'worker' },
  {
    path: '/workerHome', component: withChunkRetry(() => import('@/components/workerHome/workerHome.vue')), meta: { auth: true, type: 'worker' }, children: [
      { path: 'worker_repairCenter', component: withChunkRetry(() => import('@/components/workerHome/repairCenter/repairCenter.vue')), name: 'worker_repairCenter', meta: { auth: true, type: 'worker' } },
      { path: 'worker_repairRecord', component: withChunkRetry(() => import('@/components/workerHome/repairRecord/repairRecord.vue')), name: 'worker_repairRecord', meta: { auth: true, type: 'worker' } },
      { path: 'record_details', component: withChunkRetry(() => import('@/components/workerHome/repairRecord/recordDetails/recordDetails.vue')), name: 'record_details', meta: { auth: true, type: 'worker' } },
    ]
  },
  // 用户个人中心路由
  {
    path: '/userCenter',
    component: withChunkRetry(() => import('@/components/userHome/UserCenter/UserProfileComponent')),
    meta: { requireAuth: true, userType: 'user' }
  },
  // 维修工个人中心路由
  {
    path: '/workerCenter',
    component: withChunkRetry(() => import('@/components/workerHome/UserCenter/WorkerProfileComponent')),
    meta: { requireAuth: true, userType: 'worker' }
  }
]
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 添加全局路由导航钩子
router.beforeEach((to, from, next) => {
  // 开始加载进度条
  NProgress.start()
  
  // 在导航前尝试清理可能的观察者
  if (window.observer) {
    try {
      window.observer.disconnect();
      window.observer = null;
    } catch (e) {
      console.log('路由切换时清理observer发生错误:', e);
    }
  }
  
  // 继续导航
  next();
});

// 路由后置钩子，结束进度条
router.afterEach(() => {
  NProgress.done()
})

router.beforeEach((to, from, next) => {
  // 登录页和注册页不做拦截
  if (to.name === 'AccountLogin' || to.name === 'AccountRegister') {
    next();
    return;
  }
  
  // 确定目标路由所需的用户类型
  const requiredType = to.meta.type;
  
  // 如果路由需要特定用户类型
  if (requiredType) {
    // 检查该类型用户是否已登录
    const typeToken = localStorage.getItem(`satoken_${requiredType}`);
    
    if (!typeToken) {
      ElMessage.warning('请先登录所需类型的账户');
      next({ name: 'AccountLogin' });
      NProgress.done();
      return;
    }
    
    // 如果已登录，切换到该用户类型
    localStorage.setItem("currentLoginType", requiredType);
    
    // 确认用户信息存在
    try {
      const userInfo = JSON.parse(localStorage.getItem(`userInfo_${requiredType}`));
      if (!userInfo || userInfo.loginType !== requiredType) {
        ElMessage.error('用户类型不匹配，请重新登陆');
        next({ name: 'AccountLogin' });
        NProgress.done();
        return;
      }
    } catch (e) {
      ElMessage.error('用户信息获取失败，请重新登录');
      next({ name: 'AccountLogin' });
      NProgress.done();
      return;
    }
    
    next();
    return;
  }
  
  // 如果路由不需要特定用户类型，只需验证是否登录
  const currentType = localStorage.getItem("currentLoginType") || 'user';
  const satoken = localStorage.getItem(`satoken_${currentType}`);
  
  if (to.meta.auth && !satoken) {
    ElMessage.warning('请先行登录系统');
    next({ name: 'AccountLogin' });
    NProgress.done();
    return;
  }
  
  next();
})

export default router
